package com.dmz.questysf.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


/**
 * @desc : HTTP请求封装，建议直接使用sdk的API
 * @author: lee
 */
@Slf4j
public class HttpHelper {

    /**
     * @param url
     * @return JSONObject
     * @desc �?1.发起GET请求
     */
    public static JSONObject doGet(String url) {

        // 1.生成�?个请�?
        HttpGet httpGet = new HttpGet(url);
        // 2.配置请求 // 2000
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
        httpGet.setConfig(requestConfig);

        // 3.发起请求，获取响应信�?
        // 3.1 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            // 3.2 发起请求，获取响应信�?
            response = httpClient.execute(httpGet, new BasicHttpContext());

            // 如果返回结果的code不等�?200，说明出错了
            if (response.getStatusLine().getStatusCode() == 422) {

                log.info("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                return null;
            } else if (response.getStatusLine().getStatusCode() == 404) {
                JSONObject result = new JSONObject();
                result.put("ResponseText", "{'status':'f','errors':'无效的办件编号(包括开户通知书编号、监管编号、交款通知书编号、拨付通知书编号等)'}");
                return result;
            } else if (response.getStatusLine().getStatusCode() == 401) {
                JSONObject result = new JSONObject();
                result.put("ResponseText", "{'status':'f','errors':'apikey 错误'}");
                return result;
            } else if (response.getStatusLine().getStatusCode() == 400) {
                JSONObject result = new JSONObject();
                result.put("ResponseText", "{'status':'f','errors':'无效的json格式请求'}");
                return result;
            } else if (response.getStatusLine().getStatusCode() == 422) {
                JSONObject result = new JSONObject();
                result.put("ResponseText", "{'status':'f','errors':'数据内容错误'}");
                return result;
            } else if (response.getStatusLine().getStatusCode() == 500) {
                JSONObject result = new JSONObject();
                result.put("ResponseText", "{'status':'f','errors':'500程序错误'}");
                return result;
            } else if (response.getStatusLine().getStatusCode() == 200) {
                // 4.解析请求结果
                HttpEntity entity = response.getEntity(); // reponse返回的数据在entity�?
                if (entity != null) {
                    String resultStr = EntityUtils.toString(entity, "utf-8"); // 将数据转化为string格式
                    JSONObject result = JSONUtil.parseObj(resultStr); // 将String转换�?
                    JSONObject result1 = new JSONObject(); // 将String转换�?
                    result.put("status", "s");
                    result.put("errors", "");
                    result1.put("ResponseText", result);
                    return result1;
                }
            } else {
                System.out.println(response.getStatusLine().getStatusCode());
                JSONObject result = new JSONObject();
                result.put("ResponseText", "{'status':'f','errors':'未知错误'}");
                return result;
            }

        } catch (IOException e) {
            log.info("request url=" + url + ", exception, msg=" + e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close(); // 释放资源

                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }

        }

        return null;
    }

    /**
     * @param url
     * @return String
     * @throws Exception
     * @desc �?2.发起GET请求
     */
    public static String doGetStr(String url) throws Exception {

        // 1.生成�?个请�?
        HttpGet httpGet = new HttpGet(url);
        // 2.配置请求的属�?
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();// 2000
        httpGet.setConfig(requestConfig);

        // 3.发起请求，获取响应信�?
        // 3.1 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            // 3.2 发起请求，获取响应信�?
            response = httpClient.execute(httpGet, new BasicHttpContext());

            // 如果返回结果的code不等�?200，说明出错了
            if (response.getStatusLine().getStatusCode() != 200) {

                log.info("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                return null;
            }
            // 4.解析请求结果
            HttpEntity entity = response.getEntity(); // reponse返回的数据在entity�?
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8"); // 将数据转化为string格式
                return resultStr;
            }
        } catch (IOException e) {
            log.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null)
                try {
                    response.close(); // 释放资源
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }

    /**
     * 3.发起POST请求
     *
     * @param url  请求url
     * @param data 请求参数（json�?
     * @return
     * @throws Exception JSONObject
     * @desc �?
     */
    public static JSONObject doPost(String url, Object data) throws Exception {
        // 1.生成�?个请�?
        HttpPost httpPost = new HttpPost(url);

        // 2.配置请求属�??
        // 2.1 设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
        httpPost.setConfig(requestConfig);
        // 2.2 设置数据传输格式-json
        httpPost.addHeader("Content-Type", "application/json");
        // 2.3 设置请求参数
        StringEntity requestEntity = new StringEntity(JSONUtil.toJsonStr(data), "utf-8");
        httpPost.setEntity(requestEntity);

        // 3.发起请求，获取响应信�?
        // 3.1 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {

            // 3.3 发起请求，获取响�?
            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                log.info("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                return null;
            }

            // 获取响应内容
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                log.info("POST请求结果�?" + resultStr);

                // 解析响应内容
                JSONObject result = JSONUtil.parseObj(resultStr);

                if (result.getInt("errcode") == null) {
                    return result;
                } else if (0 == result.getInt("errcode")) {
                    return result;
                } else {
                    log.info("request url=" + url + ",return value=");
                    log.info(resultStr);
                    int errCode = result.getInt("errcode");
                    String errMsg = result.getStr("errmsg");
                    throw new Exception("error code:" + errCode + ", error message:" + errMsg);
                }
            }
        } catch (IOException e) {
            log.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null)
                try {
                    response.close(); // 释放资源

                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        return null;
    }

    /**
     * 4.发起POST请求
     *
     * @param url  请求url
     * @param data 请求参数（json�?
     * @return String
     * @throws Exception
     * @desc �?
     */
    public static String doPostStr(String url, Object data) throws Exception {
        // 1.生成�?个请�?
        HttpPost httpPost = new HttpPost(url);

        // 2.配置请求属�??
        // 2.1 设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
        httpPost.setConfig(requestConfig);
        // 2.2 设置数据传输格式-json
        httpPost.addHeader("Content-Type", "application/json");
        // 2.3 设置请求参数
        StringEntity requestEntity = new StringEntity(JSONUtil.toJsonStr(data), "utf-8");
        httpPost.setEntity(requestEntity);

        // 3.发起请求，获取响应信�?
        // 3.1 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {

            // 3.3 发起请求，获取响�?
            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                log.info("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                return null;
            }

            // 获取响应内容
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                return resultStr;
            }
        } catch (IOException e) {
            log.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null)
                try {
                    response.close(); // 释放资源

                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        return null;
    }

    /**
     * 5.发起POST请求
     *
     * @param url  请求url
     * @return
     * @throws Exception JSONObject
     * @desc �?
     */
    public static JSONObject doPost2(String url, String json) throws Exception {
        // 1.生成�?个请�?
        HttpPost httpPost = new HttpPost(url);

        // 2.配置请求属�??
        // 2.1 设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
        httpPost.setConfig(requestConfig);
        // 2.2 设置数据传输格式-json
        httpPost.addHeader("Content-Type", "application/json");
        // 2.3 设置请求参数
        StringEntity requestEntity = new StringEntity(json, "utf-8");
        httpPost.setEntity(requestEntity);

        // 3.发起请求，获取响应信�?
        // 3.1 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {

            // 3.3 发起请求，获取响�?
            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                log.info("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                return null;
            }

            // 获取响应内容
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                log.info("POST请求结果�?" + resultStr);

                // 解析响应内容
                JSONObject result = JSONUtil.parseObj(resultStr);

                if (result.getInt("errcode") == null) {
                    return result;
                } else if (0 == result.getInt("errcode")) {
                    return result;
                } else {
                    log.info("request url=" + url + ",return value=");
                    log.info(resultStr);
                    int errCode = result.getInt("errcode");
                    String errMsg = result.getStr("errmsg");
                    throw new Exception("error code:" + errCode + ", error message:" + errMsg);
                }
            }
        } catch (IOException e) {
            log.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null)
                try {
                    response.close(); // 释放资源

                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        return null;
    }


    /**
     * @param url     请求url
     * @param fileDir 下载路径
     * @return
     * @throws Exception File
     * @desc �? 7.下载文件 -get
     */
    @SuppressWarnings("deprecation")
    public static File downloadMedia(String url, String fileDir) throws Exception {
        // 1.生成�?个请�?
        HttpGet httpGet = new HttpGet(url);
        // 2.配置请求属�??
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
        httpGet.setConfig(requestConfig);

        // 3.发起请求，获取响应信�?
        // 3.1 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        // 4.设置本地保存的文�?
        // File file = new File(fileDir);
        File file = null;
        try {
            // 5. 发起请求，获取响应信�?
            response = httpClient.execute(httpGet, new BasicHttpContext());
            log.info("HttpStatus.SC_OK:" + HttpStatus.SC_OK);
            log.info("response.getStatusLine().getStatusCode():" + response.getStatusLine().getStatusCode());
            log.info("http-header:" + JSONUtil.toJsonStr(response.getAllHeaders()));
            log.info("http-filename:" + getFileName(response));

            // 请求成功
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

                // 6.取得请求内容
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    // 这里可以得到文件的类�? 如image/jpg /zip /tiff 等等
                    // 但是发现并不是十分有效，有时明明后缀�?.rar但是取到的是null，这点特别说�?
                    // 可以判断是否是文件数据流

                    // 6.1 输出�?
                    // 6.1.1获取文件名，拼接文件路径
                    String fileName = getFileName(response);
                    fileDir = fileDir + fileName;
                    file = FileUtil.newFile(fileDir);
                    // 6.1.2根据文件路径获取输出�?
                    FileOutputStream output = new FileOutputStream(file);

                    // 6.2 输入流：从钉钉服务器返回的文件流，得到网络资源并写入文件
                    InputStream input = entity.getContent();

                    // 6.3 将数据写入文件：将输入流中的数据写入到输出流
                    byte b[] = new byte[1024];
                    int j = 0;
                    while ((j = input.read(b)) != -1) {
                        output.write(b, 0, j);
                    }
                    output.flush();
                    output.close();
                }
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        } catch (IOException e) {
            log.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null)
                try {
                    response.close(); // 释放资源

                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        return file;
    }

    /**
     * @param url     请求url
     * @param data    post请求参数
     * @param fileDir 文件下载路径
     * @return
     * @throws Exception File
     * @desc �? 8.下载文件 - post
     */
    @SuppressWarnings("deprecation")
    public static File downloadMedia(String url, Object data, String fileDir) throws Exception {
        // 1.生成�?个请�?
        HttpPost httpPost = new HttpPost(url);

        // 2.配置请求属�??
        // 2.1 设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
        httpPost.setConfig(requestConfig);
        // 2.2 设置数据传输格式-json
        httpPost.addHeader("Content-Type", "application/json");
        // 2.3 设置请求参数
        StringEntity requestEntity = new StringEntity(JSONUtil.toJsonStr(data), "utf-8");
        httpPost.setEntity(requestEntity);

        // 3.发起请求，获取响应信�?
        // 3.1 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        // 4.设置本地保存的文�?
        // File file = new File(fileDir);
        File file = null;
        try {
            // 5. 发起请求，获取响应信�?
            response = httpClient.execute(httpPost, new BasicHttpContext());
            log.info("HttpStatus.SC_OK:" + HttpStatus.SC_OK);
            log.info("response.getStatusLine().getStatusCode():" + response.getStatusLine().getStatusCode());
            log.info("http-header:" + JSONUtil.toJsonStr(response.getAllHeaders()));
            log.info("http-filename:" + getFileName(response));

            // 请求成功
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

                // 6.取得请求内容
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    // 这里可以得到文件的类�? 如image/jpg /zip /tiff 等等
                    // 但是发现并不是十分有效，有时明明后缀�?.rar但是取到的是null，这点特别说�?
                    // 可以判断是否是文件数据流

                    // 6.1 输出�?
                    // 6.1.1获取文件名，拼接文件路径
                    String fileName = getFileName(response);
                    fileDir = fileDir + fileName;
                    file = FileUtil.newFile(fileDir);
                    // 6.1.2根据文件路径获取输出�?
                    FileOutputStream output = new FileOutputStream(file);

                    // 6.2 输入流：从钉钉服务器返回的文件流，得到网络资源并写入文件
                    InputStream input = entity.getContent();

                    // 6.3 将数据写入文件：将输入流中的数据写入到输出流
                    byte b[] = new byte[1024];
                    int j = 0;
                    while ((j = input.read(b)) != -1) {
                        output.write(b, 0, j);
                    }
                    output.flush();
                    output.close();
                }
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        } catch (IOException e) {
            log.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null)
                try {
                    response.close(); // 释放资源

                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        return file;
    }

    /**
     * 9. 获取response header中Content-Disposition中的filename�?
     *
     * @param response 响应
     * @return String
     * @desc �?
     */
    public static String getFileName(HttpResponse response) {
        Header contentHeader = response.getFirstHeader("Content-Disposition");
        String filename = null;
        if (contentHeader != null) {
            HeaderElement[] values = contentHeader.getElements();
            if (values.length == 1) {
                NameValuePair param = values[0].getParameterByName("filename");
                if (param != null) {
                    try {
                        // filename = new
                        // String(param.getValue().toString().getBytes(),
                        // "utf-8");
                        // filename=URLDecoder.decode(param.getValue(),"utf-8");
                        filename = param.getValue();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return filename;
    }

    public static JSONObject doPost3(String url, String json, String contentType) throws Exception {
        // 1.生成�?个请�?
        HttpPost httpPost = new HttpPost(url);

        // 2.配置请求属�??
        // 2.1 设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
        httpPost.setConfig(requestConfig);
        // 2.2 设置数据传输格式-json
        httpPost.addHeader("Content-Type", contentType);
        // 2.3 设置请求参数
        StringEntity requestEntity = new StringEntity(json, "utf-8");
        httpPost.setEntity(requestEntity);

        // 3.发起请求，获取响应信�?
        // 3.1 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {

            // 3.3 发起请求，获取响�?
            response = httpClient.execute(httpPost, new BasicHttpContext());

            // 如果返回结果的code不等�?200，说明出错了
            log.info("返回code" + response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() == 422) {
                HttpEntity entity = response.getEntity();
                String resultStr = EntityUtils.toString(entity, "utf-8"); // 将数据转化为string格式
                JSONObject result = JSONUtil.parseObj(resultStr); // 将String转换�?
                JSONObject result1 = new JSONObject(); // 将String转换�?
                result1.put("ResponseText", result);
                return result1;
            } else if (response.getStatusLine().getStatusCode() == 404) {
                JSONObject result = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                result.put("ResponseText", "{'status':'f','errors':'无效的办件编号(包括开户通知书编号、监管编号、交款通知书编号、拨付通知书编号等)'}");
                return result;
            } else if (response.getStatusLine().getStatusCode() == 401) {
                JSONObject result = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                result.put("ResponseText", "{'status':'f','errors':'apikey 错误'}");
                return result;
            } else if (response.getStatusLine().getStatusCode() == 400) {
                JSONObject result = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                result.put("ResponseText", "{'status':'f','errors':'无效的json格式请求'}");
                return result;
            } else if (response.getStatusLine().getStatusCode() == 422) {
                JSONObject result = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                result.put("ResponseText", "{'status':'f','errors':'数据内容错误'}");
                return result;
            } else if (response.getStatusLine().getStatusCode() == 500) {
                JSONObject result = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                result.put("ResponseText", "{'status':'f','errors':'500程序错误'}");
                return result;
            } else if (response.getStatusLine().getStatusCode() == 200) {
                // 4.解析请求结果
                HttpEntity entity = response.getEntity(); // reponse返回的数据在entity�?
                if (entity != null) {
                    String resultStr = EntityUtils.toString(entity, "utf-8"); // 将数据转化为string格式
                    JSONObject result = JSONUtil.parseObj(resultStr); // 将String转换�?
                    JSONObject result1 = new JSONObject(); // 将String转换�?
                    result.put("status", "s");
                    result.put("errors", "");
                    result1.put("ResponseText", result);
                    return result1;
                }
            } else {
                System.out.println(response.getStatusLine().getStatusCode());
                JSONObject result = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                result.put("ResponseText", "{'status':'f','errors':'未知错误'}");
                return result;
            }

            // 获取响应内容
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                log.info("POST请求结果�?" + resultStr);

                // 解析响应内容
                JSONObject result = JSONUtil.parseObj(resultStr);

                if (result.getInt("errcode") == null) {
                    return result;
                } else if (0 == result.getInt("errcode")) {
                    return result;
                } else {
                    log.info("request url=" + url + ",return value=");
                    log.info(resultStr);
                    int errCode = result.getInt("errcode");
                    String errMsg = result.getStr("errmsg");
                    throw new Exception("error code:" + errCode + ", error message:" + errMsg);
                }
            }
        } catch (IOException e) {
            log.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null)
                try {
                    response.close(); // 释放资源

                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        return null;
    }

    /**
     * 发�?�POST方法的请�?
     *
     * @param url  发�?�请求的 URL
     * @return
     */
    public static String post(String url, String body) {
        return post(url, null, null, body, null, null);
    }

    /**
     * @param url    发�?�请求的 URL
     * @param header
     * @param body
     * @return
     */
    public static String post(String url, Map<String, String> header, String body) {
        return post(url, header, null, body, null, null);
    }

    /**
     * @param url     发�?�请求的 URL
     * @param header
     * @param body
     * @param charset 编码格式
     * @return
     */
    public static String post(String url, Map<String, String> header, String body, String charset) {
        return post(url, header, null, body, charset, null);
    }

    /**
     * @param url         发�?�请求的 URL
     * @param header
     * @param body
     * @param charset     编码格式
     * @param contentType
     * @return
     */
    public static String post(String url, Map<String, String> header, String body, String charset, String contentType) {
        return post(url, header, null, body, charset, contentType);
    }


    /**
     * 向指�? URL 发�?�POST方法的请�?
     *
     * @param url         发�?�请求的 URL
     * @param header
     * @param mapGetParam GET请求参数，请求参数应该是?name1=value1&name2=value2 的形式�??
     * @param body        POST的数�?
     * @param charset     编码格式
     * @param contentType Content-Type �?
     * @return
     */
    public static String post(String url, Map<String, String> header, Map<String, String> mapGetParam, String body,
                              String charset, String contentType) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = null;
        try {
            String urlNameString = url + mapToGetParam(mapGetParam);
            URL realUrl = new URL(urlNameString);
            log.info("调试-访问地址:" + realUrl.toString());

            // 如果是https请求,忽略不受信任证书
            isHTTPS(url);
            // 打开和URL之间的连�?
            URLConnection connection = realUrl.openConnection();
            connection.setConnectTimeout(1000 * 10);
            connection.setReadTimeout(1000 * 10);
            // 设置通用的请求属�?
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");

            if ("".equals(contentType) || null == contentType) {
                connection.setRequestProperty("Content-Type", "application/json");
            } else {
                connection.setRequestProperty("Content-Type", contentType);
            }

            if (header != null) {
                Set<Entry<String, String>> headerEntrySet = header.entrySet();
                for (Entry<String, String> headerEntry : headerEntrySet) {
                    connection.setRequestProperty(headerEntry.getKey(), headerEntry.getValue());
                }
            }
            // 发�?�POST请求必须设置如下两行
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(connection.getOutputStream());
            // 发�?�请求参�?
            //log.info("调试-POST请求参数:" + body);
            out.print(body);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响�?
            if ("".equals(charset) || null == charset) {
                charset = "UTF-8";
            }
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
            String line;
            result = new StringBuilder();
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("post fail");
            log.error("错误-发�?�POST请求失败:" + e);
        }
        // 使用finally块来关闭输出流�?�输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
            }
        }
        if (null != result) {
            log.info("调试-POST请求返回:" + result.toString());
            return result.toString();
        }
        return "";
    }

    /**
     * 将map转换为GET请求参数
     *
     * @param map
     * @return
     */
    public static String mapToGetParam(Map<String, String> map) {
        if (map == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.append("?");
        for (Entry<String, String> entry : map.entrySet()) {
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue());
            sb.append("&");
        }
        // 减去�?后一�?"&"
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    /**
     * 将map转换为POST请求参数
     *
     * @param map
     * @return
     */
    public static String mapToPostParam(Map<String, String> map) {
        if (map == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (Entry<String, String> entry : map.entrySet()) {
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue());
            sb.append("&");
        }
        // 减去�?后一�?"&"
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    /**
     * 如果是https请求,忽略不受信任证书
     *
     * @param url
     */
    private static void isHTTPS(String url) {
        if (url.startsWith("https")) {
            try {
                ignoreSSL();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 忽略HTTPS请求的SSL证书，必须在openConnection之前调用
     *
     * @throws Exception
     */
    public static void ignoreSSL() throws Exception {
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        trustAllHttpsCertificates();
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }

    private static void trustAllHttpsCertificates() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    static class miTM implements TrustManager, X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
            return;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
            return;
        }
    }

}